package com.lsh.ofc.provider.rest.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.base.common.json.JsonUtils2;
import com.lsh.base.common.model.CommonResult;
import com.lsh.ofc.api.dto.KafkaConsumerRecordDTO;
import com.lsh.ofc.core.constant.Constants;
import com.lsh.ofc.core.handler.CreateSumSoObdHandler;
import com.lsh.ofc.core.model.DmgSoObdVo;
import com.lsh.ofc.core.redis.RedisTemplate;
import com.lsh.ofc.provider.rest.service.CollectOrderSoObdRestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.text.MessageFormat;

/**
 * Project Name: lsh-ofc
 *
 * @author peter
 * @date 19/3/29
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Service(protocol = "rest", validation = "true")
@Path("/so/collect")
@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
@Slf4j
public class CollectOrderSoObdRestServiceImpl implements CollectOrderSoObdRestService {

    @Autowired
    private CreateSumSoObdHandler sumSoObdHandler;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 创建返仓RO
     *
     * @param recordDTO
     * @return
     * @throws BusinessException
     */
    @POST
    @Path("/push")
    @Override
    public CommonResult<Boolean> createOrderSoObd(KafkaConsumerRecordDTO recordDTO) throws BusinessException {

        final String messageId = recordDTO.getMessageId();
        log.info("messageId : {} 开始处理so obd 汇总信息 , 参数为 {}", messageId, JsonUtils2.obj2Json(recordDTO));

        try {

            if (!redisTemplate.lock(MessageFormat.format(Constants.OFC_SO_SUM_LOCK, messageId), 30)) {

                log.info("messageId = " + messageId + "信息处理中。。。");
            }

            //具体kafka数据
            String json = recordDTO.getMessage();
            log.info("[物美 so obd 汇总信息为]:" + json);
            final DmgSoObdVo dmgSoObdVo = JsonUtils.json2Obj(json, DmgSoObdVo.class);
            log.info("[物美 so obd 汇总信息为]:" + dmgSoObdVo.toString());

            redisTemplate.set(this.getKey(messageId), json);

            //插入数据库
            int success = sumSoObdHandler.process(dmgSoObdVo);

            if (success > 0) {
                redisTemplate.del(this.getKey(messageId));
            }
        } catch (Exception e) {
            log.error("[物美 so obd 汇总信息为] 异常", e);
        }

        return null;
    }

    private String getKey(String messageId) {
        return MessageFormat.format(Constants.OFC_SO_SUM_KEY, messageId);
    }

}
